package com.springcloud.tread.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.springcloud.tread.pojo.Index;
import com.springcloud.tread.pojo.IndexData;
import com.springcloud.tread.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@CacheConfig(cacheNames = "index-datas")
public class IndexDataService {

    @Autowired
    RestTemplate restTemplate;

    private List<IndexData> list;

    //刷新数据
    @HystrixCommand(fallbackMethod = "hystrixSetIndexData")
    public List<IndexData> fresh(String id){
         list= getData(id);
         IndexDataService indexDataService= SpringContextUtil.getBean(IndexDataService.class);
         indexDataService.reomve(id);
         return indexDataService.store(id);
    }

    //删除
    @CacheEvict(key = "'index-data-'+#p0") //删除所有缓存
    public  void reomve(String id){

    }

    //保存
    @Cacheable(key="'index-data-'+#p0")
    public  List<IndexData> store(String id){
        return list;  //第一次调用会把数据保存到缓存当中
    }

    //从缓存中获取
    @Cacheable(key="'index-data-'+#p0")//先查看缓存中是否有数据,有则直接返回，没有则调用方法，方法返回的是一个空的list,同步到reids缓存
    public  List<IndexData> get(String id){
        return CollUtil.toList();
    }


    //调取数据
    public List<IndexData> getData(String id) {
        List<Map> lists = restTemplate.getForObject("http://localhost:7010/indexes/" + id + ".json", List.class);
        return get(lists);
    }

    public List<IndexData> get(List<Map> lists) {
        List<IndexData> list= new ArrayList<>();
        for (Map map : lists) {
            String date = map.get("date").toString();
            float closePoint = Convert.toFloat(map.get("closePoint"));
            IndexData indexData = new IndexData();
            indexData.setDate(date);
            indexData.setClosePoint(closePoint);
            list.add(indexData);
        }
        return list;
    }

    public List<IndexData> hystrixSetIndexData(String id){
         List<IndexData> list= new ArrayList<>();
          IndexData indexData= new IndexData();
          indexData.setDate("无信息！！");
          indexData.setClosePoint(0);
          list.add(indexData);
          return  list;
    }
}
